package com.yachang.qym.usbhost.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.inner.GeoPoint;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.github.nkzawa.emitter.Emitter;
import com.snappydb.DB;
import com.snappydb.SnappydbException;
import com.squareup.leakcanary.RefWatcher;
import com.yachang.qym.usbhost.R;
import com.yachang.qym.usbhost.UsbApplication;
import com.yachang.qym.usbhost.activity.BNDemoGuideActivity;
import com.yachang.qym.usbhost.adapter.FirePointAdapter;
import com.yachang.qym.usbhost.adapter.NetContactAdapter;
import com.yachang.qym.usbhost.model.CallHelpModel;
import com.yachang.qym.usbhost.model.FirePointModel;
import com.yachang.qym.usbhost.model.LocationModel;
import com.yachang.qym.usbhost.model.MakerModel;
import com.yachang.qym.usbhost.model.OutPoliceModel;
import com.yachang.qym.usbhost.model.UserModel;
import com.yachang.qym.usbhost.utils.API;
import com.yachang.qym.usbhost.utils.AllData;
import com.yachang.qym.usbhost.utils.DataTransfer;
import com.yachang.qym.usbhost.utils.DistanceDTSUtil;
import com.yachang.qym.usbhost.utils.LoadImage;
import com.yachang.qym.usbhost.utils.MyOrientationListener;
import com.yachang.qym.usbhost.utils.NotificationCenter;
import com.yachang.qym.usbhost.utils.SendData;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.gson.Gson;
import com.yachang.qym.usbhost.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import de.hdodenhof.circleimageview.CircleImageView;

import static com.baidu.navisdk.adapter.BaiduNaviManager.RoutePlanPreference.ROUTE_PLAN_MOD_AVOID_TAFFICJAM;
import static com.baidu.navisdk.adapter.BaiduNaviManager.RoutePlanPreference.ROUTE_PLAN_MOD_RECOMMEND;
import static com.baidu.navisdk.adapter.PackageUtil.getSdcardDir;
import static com.yachang.qym.usbhost.utils.API.mSocket;
import static java.lang.System.in;

/**
 * Created by qinyuanmao on 16/5/25.
 */
public class OutPoliceFragment extends Fragment{

    private MapView mMapView;
    private ImageView ivMyLocation;
    private TextView mTvCallHelp;
    private RecyclerView mFloorRecyclerView;
    private FloatingActionButton mFabShowFloor;
    private LocationClient mLocationClient;
    private MyLocationListener mLocationListener;
    private BitmapDescriptor mIconLocation;
    private MyOrientationListener myOrientationListener;
    private TextView mMyWormates;
    private float mCurrentX;
    private MyLocationConfiguration.LocationMode mLocationMode;
    private GoogleApiClient client;
    private double mLatitude;
    private double mLongitude;

    private boolean isFirstIn = true;
    private boolean isFloorShow = false;
    private BaiduMap mBaiduMap;
    private View mParentView;
    private RelativeLayout mLayoutNeedHelp;
    private TextView mLayoutFirePoint;
    private TextView mTvNeedHelp;
    private Boolean isRemote = false;

    private List<LocationModel> nearLocation = new ArrayList<>();
    private List<LocationModel> locationModelList = new ArrayList<>();
    private Map<String,Bitmap> markersBitmap = new HashMap<>();
    private Map<String,Bitmap> usersBitmap = new HashMap<>();
    private Map<String,Marker> outMarker = new HashMap<>();
    private Map<String,OutPoliceModel> outPoliceModelMap = new ConcurrentHashMap<>();
    private Map<String,OutPoliceModel> remoteHelpModelMap = new ConcurrentHashMap<>();
    private Map<String,CallHelpModel> callHelpModelMap = new ConcurrentHashMap<>();
    private List<MakerModel> makerModels = new ArrayList<MakerModel>();
    private List<UserModel> userModels = new ArrayList<>();
    private boolean autoCenter = true;

    private Emitter.Listener onEnterPolice = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            if(getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        OutPoliceModel data = new OutPoliceModel();
                        Gson gson = new Gson();
                        JSONObject jsonObject = (JSONObject) args[0];
                        try {
                            JSONObject result = jsonObject.getJSONObject("result");
                            data = gson.fromJson(String.valueOf(result), OutPoliceModel.class);
                            for (OutPoliceModel model : outPoliceModelMap.values()) {
                                if (model.getUid().equals(data.getUid())) {
                                    outMarker.get(model.get_id()).remove();
                                    outPoliceModelMap.remove(model);
                                    break;
                                }
                            }
                            overLayUser(data);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    };

    private Emitter.Listener onChangeAddress = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            if(getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        OutPoliceModel data = new OutPoliceModel();
                        Gson gson = new Gson();
                        JSONObject jsonObject = (JSONObject) args[0];
                        data = gson.fromJson(String.valueOf(jsonObject), OutPoliceModel.class);
                        overLayUser(data);
                    }
                });
            }
        }
    };

    private Emitter.Listener onExitPolice = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            if(getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        OutPoliceModel data = new OutPoliceModel();
                        Gson gson = new Gson();
                        JSONObject jsonObject = (JSONObject) args[0];
                        data = gson.fromJson(String.valueOf(jsonObject), OutPoliceModel.class);
                        if (!data.getUid().equals(AllData.userModel.get_id()) && !data.getUid().equals("exit")) {
                            if (outMarker.containsKey(data.get_id()))
                                outMarker.get(data.get_id()).remove();
                            if (outPoliceModelMap.containsKey(data.get_id()))
                                outPoliceModelMap.remove(data.get_id());
                        }
                    }
                });
            }
        }
    };

    private Emitter.Listener onUploadInfo = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            if(getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        OutPoliceModel data = new OutPoliceModel();
                        Gson gson = new Gson();
                        JSONObject jsonObject = (JSONObject) args[0];
                        data = gson.fromJson(String.valueOf(jsonObject), OutPoliceModel.class);
                        overLayUser(data);
                    }
                });
            }
        }
    };

    private Emitter.Listener onEnterHelp = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            if(getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = (JSONObject) args[0];
                        CallHelpModel model = new CallHelpModel();
                        Gson gson = new Gson();
                        model = gson.fromJson(String.valueOf(jsonObject), CallHelpModel.class);
                        if (model.getUid().equals(AllData.userModel.get_id())) {
                            AllData.myCallHelpModel = model;
                            mTvNeedHelp.setText(getResources().getText(R.string.exit_help));
                            mLayoutNeedHelp.setBackground(getResources().getDrawable(R.drawable.btn_cancel));
                            if (!isRemote) {
                                SendData.data = SendData.enterNeedHelp();
                                SendData.needSend = true;
                            }
                            isRemote = false;
                        } else {
                            callHelpModelMap.put(model.getOid(), model);
                        }
                    }
                });
            }
        }
    };

    private Emitter.Listener onExitHelp = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            CallHelpModel data = new CallHelpModel();
            Gson gson = new Gson();
            JSONObject jsonObject = (JSONObject) args[0];
            data = gson.fromJson(String.valueOf(jsonObject), CallHelpModel.class);
            if(callHelpModelMap.containsKey(data.getOid()))
                callHelpModelMap.remove(data.getOid());
        }
    };

    private Emitter.Listener onMyExitHelp = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            if(getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CallHelpModel data = new CallHelpModel();
                        Gson gson = new Gson();
                        JSONObject jsonObject = (JSONObject) args[0];
                        data = gson.fromJson(String.valueOf(jsonObject), CallHelpModel.class);
                        if (data.getOid().equals(AllData.outPolice_id)){
                            mTvNeedHelp.setText(getResources().getText(R.string.enter_help));
                            mLayoutNeedHelp.setBackground(getResources().getDrawable(R.drawable.bg_btn_no_tran));
                            mLayoutNeedHelp.setClickable(false);
                            SendData.data = SendData.exitNeedHelp();
                            SendData.needSend = true;
                            AllData.needHelp = false;
                        }
                    }
                });
            }
        }
    };

    private Emitter.Listener onFirePoint = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            //获取报警点信息，推送到通知栏，开启导航功能
            FirePointModel model = new FirePointModel();
            Gson gson = new Gson();
            JSONObject jsonObject = (JSONObject) args[0];
            model = gson.fromJson(String.valueOf(jsonObject), FirePointModel.class);
            AllData.firePointModels.add(model);
            overLayFirePoint(model);
        }
    };
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mParentView = inflater.inflate(R.layout.fragment_out_police, container, false);
        NotificationCenter.getInstance().addObserver("changeHelpState", this, "changeHelpState");
        initLocation();
        client = new GoogleApiClient.Builder(getActivity()).addApi(AppIndex.API).build();
        initView();
        getMakerData();
        getFirePoint();
        return mParentView;
    }

    public void changeHelpState(){
        Message message = setMapHandler.obtainMessage();
        message.what = 3;
        setMapHandler.sendMessage(message);
    }

    private void initView(){
        mMapView = (MapView) mParentView.findViewById(R.id.bmapView);
        mMyWormates = (TextView) mParentView.findViewById(R.id.tv_my_workmates);
        ivMyLocation = (ImageView) mParentView.findViewById(R.id.iv_center_my_location);
        mLayoutNeedHelp = (RelativeLayout) mParentView.findViewById(R.id.layout_need_help);
        mLayoutFirePoint = (TextView) mParentView.findViewById(R.id.tv_fire_point);
        mTvNeedHelp = (TextView) mParentView.findViewById(R.id.tv_need_help);
        mTvCallHelp = (TextView) mParentView.findViewById(R.id.tv_help_mates);
        mFabShowFloor = (FloatingActionButton) mParentView.findViewById(R.id.fab_exchange_style);
        mFloorRecyclerView = (RecyclerView) mParentView.findViewById(R.id.recyclerview_floor);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mFloorRecyclerView.setLayoutManager(linearLayoutManager);
        mFabShowFloor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isFloorShow){
                    isFloorShow = !isFloorShow;
                    mFloorRecyclerView.setVisibility(View.GONE);
                } else {
                    isFloorShow = !isFloorShow;
                    mFloorRecyclerView.setVisibility(View.VISIBLE);
                }
            }
        });
        mBaiduMap = mMapView.getMap();
        MapStatusUpdate after = MapStatusUpdateFactory.zoomTo(15.0f);
        mBaiduMap.setMapStatus(after);
        View child = mMapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);
        }
        mBaiduMap.setOnMapLongClickListener(new BaiduMap.OnMapLongClickListener() {
            @Override
            public void onMapLongClick(final LatLng latLng) {
                GeoCoder geoCoder = GeoCoder.newInstance();
                //设置反地理编码位置坐标
                ReverseGeoCodeOption op = new ReverseGeoCodeOption();
                op.location(latLng);
                //发起反地理编码请求(经纬度->地址信息)
                geoCoder.reverseGeoCode(op);
                geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

                    @Override
                    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
                        showPositionPopup(latLng, arg0.getAddress());
                    }

                    @Override
                    public void onGetGeoCodeResult(GeoCodeResult arg0) {
                    }
                });
            }
        });
        mLayoutFirePoint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!(AllData.firePointModels.isEmpty() || AllData.firePointModels.size() < 1)){
                    showFirePointList();
                }
            }
        });
        mTvCallHelp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!(callHelpModelMap.isEmpty() || callHelpModelMap.size() < 1)){
                    showHelpPopList();
                }
            }
        });
        mMyWormates.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!outPoliceModelMap.isEmpty() || outPoliceModelMap.size() < 1){
                    showUserPopList();
                }
            }
        });
        ivMyLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                centerToMyLocation();
                autoCenter = true;
            }
        });
        mBaiduMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
                autoCenter = false;
            }
        });
        mTvNeedHelp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(AllData.isLoaddingFinish) {
                    AllData.needHelp = !AllData.needHelp;
                    if (!AllData.needHelp) {
                        cancelCallHelp();
                    } else {
                        callHelp();
                    }
                } else {
                    ToastUtil.showToast("数据正在加载中，请稍后！");
                }
            }
        });
        centerToMyLocation();
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(final Marker marker)
            {
                //获得marker中的数据
                int state =(int) marker.getExtraInfo().get("state");
                switch (state){
                    case 0:{
                        LocationModel model = (LocationModel) marker.getExtraInfo().get("info");
                        showDetailPopupWindow(model);
                    }break;
                    case 1:{
                        OutPoliceModel model = (OutPoliceModel) marker.getExtraInfo().get("info");
                        showOutDetailPopupWindow(model);
                    }break;
                    case 2:{
                        FirePointModel model = (FirePointModel) marker.getExtraInfo().get("info");
                        showFirePoint(model);
                    }
                }
                return true;
            }
        });

    }

    private void showUserPopList(){
        View contentView = LayoutInflater.from(getActivity()).inflate(
                R.layout.popup_list, null);

        ListView lvUser = (ListView) contentView.findViewById(R.id.lv_content);
        final List<OutPoliceModel> modelList = new ArrayList<>();
        for(OutPoliceModel model : outPoliceModelMap.values()){
            modelList.add(model);
        }
        if(modelList.size() > 0) {
            NetContactAdapter adapter = new NetContactAdapter(getActivity(), modelList);
            lvUser.setAdapter(adapter);
        }

        final PopupWindow popupWindow = new PopupWindow(contentView,
                (int) (getActivity().getResources().getDimension(R.dimen.one_dp) * 210), LinearLayout.LayoutParams.WRAP_CONTENT, true);

        lvUser.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                centerToOtherLocation(modelList.get(position).getLongitude(), modelList.get(position).getLatitude());
                popupWindow.dismiss();
                showOutDetailPopupWindow(modelList.get(position));
            }
        });

        popupWindow.setTouchable(true);

        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });

        popupWindow.setAnimationStyle(R.style.PopupAnimation);
        popupWindow.showAsDropDown(mMyWormates);
        popupWindow.update();
    }


    private void showFirePointList(){
        View contentView = LayoutInflater.from(getActivity()).inflate(
                R.layout.popup_list, null);

        ListView lvUser = (ListView) contentView.findViewById(R.id.lv_content);
        if(AllData.firePointModels.size() > 0) {
            FirePointAdapter adapter = new FirePointAdapter(getActivity(), AllData.firePointModels);
            lvUser.setAdapter(adapter);
        }

        final PopupWindow popupWindow = new PopupWindow(contentView,
                (int) (getActivity().getResources().getDimension(R.dimen.one_dp) * 280), LinearLayout.LayoutParams.WRAP_CONTENT, true);

        lvUser.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                centerToOtherLocation(AllData.firePointModels.get(position).getLongitude(), AllData.firePointModels.get(position).getLatitude());
                popupWindow.dismiss();
                showFirePoint(AllData.firePointModels.get(position));
            }
        });

        popupWindow.setTouchable(true);

        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });

        popupWindow.setAnimationStyle(R.style.PopupAnimation);
        popupWindow.showAsDropDown(mLayoutFirePoint);
        popupWindow.update();
    }

    private void showHelpPopList(){
        View contentView = LayoutInflater.from(getActivity()).inflate(
                R.layout.popup_list, null);

        ListView lvUser = (ListView) contentView.findViewById(R.id.lv_content);
        final List<OutPoliceModel> modelList = new ArrayList<>();
        for (String key : callHelpModelMap.keySet()) {
            modelList.add(outPoliceModelMap.get(key));
        }
        if(modelList.size() > 0) {
            NetContactAdapter adapter = new NetContactAdapter(getActivity(), modelList);
            lvUser.setAdapter(adapter);
        }

        final PopupWindow popupWindow = new PopupWindow(contentView,
                (int) (getActivity().getResources().getDimension(R.dimen.one_dp) * 210), LinearLayout.LayoutParams.WRAP_CONTENT, true);

        lvUser.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                centerToOtherLocation(modelList.get(position).getLongitude(), modelList.get(position).getLatitude());
                popupWindow.dismiss();
                showHelpDetailPopupWindow(callHelpModelMap.get(modelList.get(position).get_id()));
            }
        });

        popupWindow.setTouchable(true);

        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });

        popupWindow.setAnimationStyle(R.style.PopupAnimation);
        popupWindow.showAsDropDown(mTvCallHelp);
        popupWindow.update();
    }

    // 定位到我的位置
    private void centerToMyLocation() {
        LatLng latlng = new LatLng(mLatitude, mLongitude);
        MapStatus mMapStatus = null;
        if(isFirstIn){
            mMapStatus = new MapStatus.Builder()
                    .target(latlng)
                    .zoom(20)
                    .build();
            isFirstIn = false;
        }else {
            mMapStatus = new MapStatus.Builder()
                    .target(latlng)
                    .build();
        }
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        //改变地图状态
        mBaiduMap.setMapStatus(mMapStatusUpdate);
    }

    private void centerToOtherLocation(double longitude, double latitude){
        autoCenter = false;
        LatLng latlng = new LatLng(latitude, longitude);
        MapStatus mMapStatus = null;
        mMapStatus = new MapStatus.Builder()
                .target(latlng)
                .build();
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        //改变地图状态
        mBaiduMap.setMapStatus(mMapStatusUpdate);
    }

    @Override
    public void onStart() {
        super.onStart();
        client.connect();
        // 开始定位
        mBaiduMap.setMyLocationEnabled(true);
        if (!mLocationClient.isStarted()) {
            mLocationClient.start();
        }
        // 开启方向传感器
        myOrientationListener.start();
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();

        RefWatcher refWatcher = UsbApplication.getRefWatcher(getActivity());
        refWatcher.watch(this);
    }

    private void initLocation() {
        mLocationMode = MyLocationConfiguration.LocationMode.NORMAL;

        mLocationClient = new LocationClient(getActivity());
        mLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mLocationListener);

        LocationClientOption option = new LocationClientOption();
        option.setCoorType("bd09ll");
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        option.setScanSpan(1000);// 设置定位一秒钟请求一次；

        mLocationClient.setLocOption(option);

        // 初始化图标
        mIconLocation = BitmapDescriptorFactory
                .fromResource(R.mipmap.location);
        myOrientationListener = new MyOrientationListener(getActivity());
        myOrientationListener.setOnOrientationListener(new MyOrientationListener.OnOrientationListener() {
            @Override
            public void onOrientationChanged(float x) {
                mCurrentX = x;
            }
        });
    }

    private class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

            MyLocationData data = new MyLocationData.Builder()//
                    .direction(mCurrentX)//
                    .accuracy(location.getRadius())//
                    .latitude(location.getLatitude())//
                    .longitude(location.getLongitude())//
                    .build();

            mBaiduMap.setMyLocationData(data);

            // 设置自定义图标
            MyLocationConfiguration config = new MyLocationConfiguration(
                    mLocationMode, true, mIconLocation);
            mBaiduMap.setMyLocationConfigeration(config);

            // 更新经纬度
            mLatitude = location.getLatitude();
            mLongitude = location.getLongitude();

            if(AllData.isLogin) {
                AllData.userModel.setLongitude(location.getLongitude());
                AllData.userModel.setLatitude(location.getLatitude());
            }

            if (isFirstIn) {
                LatLng latlng = new LatLng(location.getLatitude(),
                        location.getLongitude());
                mLatitude = location.getLatitude();
                mLongitude = location.getLongitude();
                if(AllData.isLogin) {
                    AllData.userModel.setLongitude(mLongitude);
                    AllData.userModel.setLatitude(mLatitude);
                }
                MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latlng);
                mBaiduMap.animateMapStatus(msu);
            }

            if(AllData.isInPolice){
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", AllData.outPolice_id);
                map.put("longitude", AllData.userModel.getLongitude());
                map.put("latitude", AllData.userModel.getLatitude());
                map.put("high", DataTransfer.getNum(AllData.helpModel.getMachineHigh()));
                map.put("temp", DataTransfer.getNum(AllData.helpModel.getMachineTemp()));
                map.put("nowFloor", AllData.helpModel.getNowFloor());
                map.put("fid", AllData.userModel.getFirecompany_id());
                JSONObject jsonObject = new JSONObject(map);

                mSocket.emit("address", jsonObject);
            }

            if(autoCenter)
                centerToMyLocation();
        }
    }

    private void callHelp(){
        mTvNeedHelp.setText(getResources().getText(R.string.exit_help));
        mLayoutNeedHelp.setBackground(getResources().getDrawable(R.drawable.btn_cancel));
        mLayoutNeedHelp.setClickable(false);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("uid", AllData.userModel.get_id());
        map.put("mid", AllData.helpModel.getMachineID());
        map.put("oid", AllData.outPolice_id);
        map.put("high", AllData.helpModel.getMachineHigh());
        map.put("fid", AllData.userModel.getFirecompany_id());
        map.put("name", AllData.userModel.getUsername());
        map.put("image", AllData.userModel.getImageUrl());
        JSONObject jsonObject = new JSONObject(map);
        mSocket.emit("help", jsonObject);
        //硬件操作
        SendData.data = SendData.enterNeedHelp();
        SendData.needSend = true;
    }

    private void cancelCallHelp(){
        mTvNeedHelp.setText(getResources().getText(R.string.enter_help));
        mLayoutNeedHelp.setBackground(getResources().getDrawable(R.drawable.bg_btn_no_tran));
        mLayoutNeedHelp.setClickable(false);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", AllData.myCallHelpModel.get_id());
        map.put("fid", AllData.userModel.getFirecompany_id());
        JSONObject jsonObject = new JSONObject(map);
        mSocket.emit("cancelHelp", jsonObject);
        //硬件操作
        SendData.data = SendData.exitNeedHelp();
        SendData.needSend = true;
    }

    private void getMakerData(){
        if(AllData.isNetLogin) {
            makerModels = new ArrayList<>();
            JsonObjectRequest ja = new JsonObjectRequest(Request.Method.GET, API.getMakerUrl(), null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray array = response.getJSONArray("result");
                        for (int i = 0; i < array.length(); i++) {
                            MakerModel data = new MakerModel();
                            JSONObject object = array.getJSONObject(i);
                            Gson gson = new Gson();
                            data = gson.fromJson(String.valueOf(object), MakerModel.class);
                            makerModels.add(data);
                        }
                        DB db = UsbApplication.getDB();
                        Object[] markers = makerModels.toArray();
                        db.put("markers", markers);
                        getUserInfo();
                    } catch (JSONException e) {
                    } catch (SnappydbException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });
            RequestQueue queue = UsbApplication.getQueue();
            queue.add(ja);
        } else {
            DB db = UsbApplication.getDB();
            MakerModel[] markers;
            try {
                markers = db.getObjectArray("markers", MakerModel.class);
                makerModels = Arrays.asList(markers);
                getUserInfo();
            } catch (SnappydbException e) {
                e.printStackTrace();
            }
        }
    }

    Handler setMapHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 1){
                initMapDataList();
            } else if(msg.what == 3){
                if(!AllData.needHelp){
                    cancelCallHelp();
                } else {
                    callHelp();
                }
            }
        }
    };

    class GetBitmapThread extends Thread {
        @Override
        public void run() {
            Looper.prepare();
            for(int i = 0; i < makerModels.size(); i++){
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.set_location);
                if(!makerModels.get(i).getImage_url().equals("")) {
                    bitmap = LoadImage.getBitmap(makerModels.get(i).getImage_url());
                    bitmap = LoadImage.bigBitmap(bitmap);
                }
                markersBitmap.put(makerModels.get(i).get_id(), bitmap);
            }
            for(int i = 0; i < userModels.size(); i++){
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.head);
                if(!userModels.get(i).getImageUrl().equals("")) {
                    bitmap = LoadImage.getBitmap(userModels.get(i).getImageUrl());
                    bitmap = LoadImage.smallBitmap(bitmap);
                }
                usersBitmap.put(userModels.get(i).get_id(), bitmap);
            }
            AllData.userBitmap = usersBitmap;
            Message message = new Message();
            message.what = 1;
            setMapHandler.sendMessage(message);
            Looper.loop();
        }
    }

    private void overLayUser(OutPoliceModel model) {
        LatLng point = null;
        MarkerOptions option = null;
        point = new LatLng(model.getLatitude(), model.getLongitude());
        if(callHelpModelMap.containsKey(model.get_id())){
            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.sos);
            Bitmap bitmap1 = LoadImage.zoomImage(bitmap.getBitmap(), 48 * getActivity().getResources().getDimension(R.dimen.one_dp), 48 * getActivity().getResources().getDimension(R.dimen.one_dp));
            BitmapDescriptor bitmap2 = BitmapDescriptorFactory.fromBitmap(bitmap1);
            option = new MarkerOptions().position(point).icon(bitmap2);
        } else {
            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromBitmap(usersBitmap.get(model.getUid()));
            Bitmap bitmap1 = LoadImage.zoomImage(bitmap.getBitmap(), 48 * getActivity().getResources().getDimension(R.dimen.one_dp), 48 * getActivity().getResources().getDimension(R.dimen.one_dp));
            BitmapDescriptor bitmap2 = BitmapDescriptorFactory.fromBitmap(bitmap1);
            option = new MarkerOptions().position(point).icon(bitmap2);
        }
        Marker marker = (Marker) mBaiduMap.addOverlay(option);
        //Bundle用于通信
        Bundle bundle = new Bundle();
        bundle.putSerializable("info", model);
        bundle.putInt("state", 1);
        marker.setExtraInfo(bundle);//将bundle值传入marker中，给baiduMap设置监听时可以得到它
        if(keyInMap(model.get_id(), outPoliceModelMap)) { // 如果之前有的把他删掉
            outMarker.get(model.get_id()).remove();
            outMarker.remove(model.get_id());
        }
        outPoliceModelMap.put(model.get_id(), model);
        outMarker.put(model.get_id(), marker);
    }

    private boolean keyInMap(String key, Map<String, OutPoliceModel> map){
        boolean isIn = false;
        for (OutPoliceModel data : map.values()) {
            if(key.equals(data.get_id()))
                isIn = true;
        }
        return isIn;
    }

    //初始化每个覆盖物对应的信息
    private void initMapDataList() {
        if(AllData.isNetLogin) {
            locationModelList = new ArrayList<>();
            JsonObjectRequest ja = new JsonObjectRequest(Request.Method.GET, API.getLocationUrl(), null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray array = response.getJSONArray("result");
                        for (int i = 0; i < array.length(); i++) {
                            LocationModel data = new LocationModel();
                            JSONObject object = array.getJSONObject(i);
                            Gson gson = new Gson();
                            data = gson.fromJson(String.valueOf(object), LocationModel.class);
                            locationModelList.add(data);
                            if ((data.getLatitude() < mLatitude - 0.001) && (data.getLatitude() > mLatitude + 0.001))
                                if ((data.getLongitude() < mLongitude - 0.001) && (data.getLongitude() > mLongitude + 0.001)) {
                                    nearLocation.add(data);
                                }
                        }
                        DB db = UsbApplication.getDB();
                        Object[] locations = locationModelList.toArray();
                        db.put("location", locations);
                        addOverlay(locationModelList);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (SnappydbException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });
            RequestQueue queue = UsbApplication.getQueue();
            queue.add(ja);
        } else {
            try {
                DB db = UsbApplication.getDB();
                LocationModel[] locationModels1;
                locationModels1 = db.getObjectArray("locations", LocationModel.class);
                locationModelList = Arrays.asList(locationModels1);
                addOverlay(locationModelList);
            } catch (SnappydbException e) {
                e.printStackTrace();
            }
        }

        AllData.isLoaddingFinish = true;
        mSocket.on("inPolice", onEnterPolice);
        mSocket.on("address", onChangeAddress);
        mSocket.on("outPolice", onExitPolice);
        mSocket.on("uploadInfo", onUploadInfo);
        mSocket.on("help", onEnterHelp);
        mSocket.on("cancelHelp", onExitHelp);
        mSocket.on("firePoint", onFirePoint);

        mSocket.on("exitHelp", onMyExitHelp);
    }

    private void getUserInfo(){
        DB db = UsbApplication.getDB();
        UserModel[] userModels1 = new UserModel[0];
        userModels = new ArrayList<>();
        try {
            userModels1 = db.getObjectArray(AllData.userModel.getFirecompany_id(), UserModel.class);
            userModels = Arrays.asList(userModels1);
        } catch (SnappydbException e) {
            e.printStackTrace();
        }
        if(userModels == null){
            userModels = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            map.put("fid", AllData.userModel.getFirecompany_id());
            map.put("state", true);
            JSONObject jsonObject = new JSONObject(map);
            JsonObjectRequest ja = new JsonObjectRequest(Request.Method.POST, API.getUserUrl(), jsonObject, new Response.Listener<JSONObject>(){
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray array = response.getJSONArray("result");
                        for(int i = 0; i < array.length(); i++) {
                            UserModel data = new UserModel();
                            JSONObject object = array.getJSONObject(i);
                            Gson gson = new Gson();
                            data = gson.fromJson(String.valueOf(object),UserModel.class);
                            userModels.add(data);
                        }
                        GetBitmapThread thread = new GetBitmapThread();
                        thread.start();
                    } catch (JSONException e) {}
                }
            },new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {}
            });
            RequestQueue queue = UsbApplication.getQueue();
            queue.add(ja);
        } else {
            GetBitmapThread thread = new GetBitmapThread();
            thread.start();
        }
    }

    /**
     * 添加覆盖物的方法
     */
    private void addOverlay(List<LocationModel> models) {
        Marker marker = null;
        LatLng point = null;
        MarkerOptions option = null;
        for (LocationModel data : models) {
            BitmapDescriptor bitmap =  BitmapDescriptorFactory.fromBitmap(markersBitmap.get(data.getMaker_id()));
            point = new LatLng(data.getLatitude(), data.getLongitude());
            option = new MarkerOptions().position(point).icon(bitmap);
            marker = (Marker) mBaiduMap.addOverlay(option);
            //Bundle用于通信
            Bundle bundle = new Bundle();
            bundle.putSerializable("info", data);
            bundle.putInt("state", 0);
            marker.setExtraInfo(bundle);//将bundle值传入marker中，给baiduMap设置监听时可以得到它
        }
    }

    private void showPositionPopup(final LatLng latLng, final String address){
        View contentView = LayoutInflater.from(getActivity()).inflate(
                R.layout.popup_position, null);
        TextView tvAddress = (TextView) contentView.findViewById(R.id.tv_address);
        ImageView ivToPoint = (ImageView) contentView.findViewById(R.id.iv_to_point);
        TextView tvDistance = (TextView) contentView.findViewById(R.id.tv_distant);
        LatLng myPosition = new LatLng(AllData.userModel.getLatitude(), AllData.userModel.getLongitude());
        double distance = DistanceUtil.getDistance(myPosition, latLng);
        tvDistance.setText(DistanceDTSUtil.getDistance(distance));
        tvAddress.setText(address);
        ivToPoint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GeoCoder geoCoder = GeoCoder.newInstance();
                //设置反地理编码位置坐标
                ReverseGeoCodeOption op = new ReverseGeoCodeOption();
                op.location(new LatLng(AllData.userModel.getLatitude(), AllData.userModel.getLongitude()));
                //发起反地理编码请求(经纬度->地址信息)
                geoCoder.reverseGeoCode(op);
                geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

                    @Override
                    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
                        //获取点击的坐标地址
                        BNRoutePlanNode startPoint = new BNRoutePlanNode(AllData.userModel.getLongitude(), AllData.userModel.getLatitude(), arg0.getAddress(), "起始位置", BNRoutePlanNode.CoordinateType.BD09LL);
                        BNRoutePlanNode endPoint = new BNRoutePlanNode(latLng.longitude, latLng.latitude, address, "结束位置", BNRoutePlanNode.CoordinateType.BD09LL);

                        List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
                        list.add(startPoint);
                        list.add(endPoint);
                        if(BaiduNaviManager.isNaviInited())
                            BaiduNaviManager.getInstance().launchNavigator(getActivity(),
                                    list, ROUTE_PLAN_MOD_RECOMMEND, true,
                                    new DemoRoutePlanListener(startPoint));
                    }

                    @Override
                    public void onGetGeoCodeResult(GeoCodeResult arg0) {
                    }
                });
            }
        });

        PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });

        popupWindow.setAnimationStyle(R.style.PopupAnimation);
        popupWindow.showAtLocation(mMapView, Gravity.TOP, 0, 0);
        popupWindow.update();
    }

    private void showDetailPopupWindow(final LocationModel data) {

        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(getActivity()).inflate(
                R.layout.popup_show_info, null);
        // 设置按钮的点击事件

        LatLng myPosition = new LatLng(mLatitude,mLongitude);
        LatLng thisPosition = new LatLng(data.getLatitude(),data.getLongitude());
        Double distance = DistanceUtil.getDistance(myPosition, thisPosition);
        TextView tvAddress = (TextView) contentView.findViewById(R.id.tv_address);
        TextView tvDetail = (TextView) contentView.findViewById(R.id.tv_detail);
        TextView tvPosition = (TextView) contentView.findViewById(R.id.tv_position);
        TextView tvMaker = (TextView) contentView.findViewById(R.id.tv_marker);
        TextView tvAuthor = (TextView) contentView.findViewById(R.id.tv_author);
        ImageView ivImage = (ImageView) contentView.findViewById(R.id.iv_show_image);
        TextView tvDistance = (TextView) contentView.findViewById(R.id.tv_distant);
        ImageView ivToNav = (ImageView) contentView.findViewById(R.id.iv_to_point);
        for(int i = 0; i < userModels.size(); i++){
            if(data.getUser_id().equals(userModels.get(i).get_id())){
                tvAuthor.setText(userModels.get(i).getUsername());
            }
        }
        for(int i = 0; i < makerModels.size(); i++){
            if(data.getMaker_id().equals(makerModels.get(i).get_id())){
                tvMaker.setText(makerModels.get(i).getName());
            }
        }
        tvDistance.setText(DistanceDTSUtil.getDistance(distance));
        tvPosition.setText(data.getPosition());
        tvAddress.setText(data.getAddress());
        tvDetail.setText(data.getDescribe());
        ivToNav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GeoCoder geoCoder = GeoCoder.newInstance();
                //设置反地理编码位置坐标
                ReverseGeoCodeOption op = new ReverseGeoCodeOption();
                op.location(new LatLng(AllData.userModel.getLatitude(), AllData.userModel.getLongitude()));
                //发起反地理编码请求(经纬度->地址信息)
                geoCoder.reverseGeoCode(op);
                geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

                    @Override
                    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
                        //获取点击的坐标地址
                        BNRoutePlanNode startPoint = new BNRoutePlanNode(AllData.userModel.getLongitude(), AllData.userModel.getLatitude(), arg0.getAddress(), "起始位置", BNRoutePlanNode.CoordinateType.BD09LL);
                        BNRoutePlanNode endPoint = new BNRoutePlanNode(data.getLongitude(), data.getLatitude(), data.getAddress(), "结束位置", BNRoutePlanNode.CoordinateType.BD09LL);

                        List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
                        list.add(startPoint);
                        list.add(endPoint);
                        if(BaiduNaviManager.isNaviInited())
                            BaiduNaviManager.getInstance().launchNavigator(getActivity(),
                                    list, ROUTE_PLAN_MOD_RECOMMEND, true,
                                    new DemoRoutePlanListener(startPoint));
                    }

                    @Override
                    public void onGetGeoCodeResult(GeoCodeResult arg0) {
                    }
                });
            }
        });
        LoadImage.showImage(data.getImage_url(), ivImage);
        PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });

        popupWindow.setAnimationStyle(R.style.PopupAnimation);
        popupWindow.showAtLocation(mMapView, Gravity.TOP, 0, 0);
        popupWindow.update();
    }

    private void showFirePoint(final FirePointModel model){
        View contentView = LayoutInflater.from(getActivity()).inflate(
                R.layout.popup_fire_point, null);
        TextView tvAddress = (TextView) contentView.findViewById(R.id.tv_address);
        TextView tvPosition = (TextView) contentView.findViewById(R.id.tv_position);
        TextView tvPhone = (TextView) contentView.findViewById(R.id.tv_phone);
        TextView tvName = (TextView) contentView.findViewById(R.id.tv_name);
        TextView tvDetail = (TextView) contentView.findViewById(R.id.tv_detail);
        ImageView ivToPoint = (ImageView) contentView.findViewById(R.id.iv_to_point);
        TextView tvDistance = (TextView) contentView.findViewById(R.id.tv_distant);
        LatLng myPosition = new LatLng(AllData.userModel.getLatitude(), AllData.userModel.getLongitude());
        LatLng firePosition = new LatLng(model.getLatitude(), model.getLongitude());
        double distance = DistanceUtil.getDistance(myPosition, firePosition);
        tvDistance.setText(DistanceDTSUtil.getDistance(distance));
        tvAddress.setText(model.getAddress());
        tvDetail.setText(model.getDetail());
        tvName.setText(model.getName());
        tvPhone.setText(model.getPhone());
        tvPosition.setText(model.getPosition());
        ivToPoint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GeoCoder geoCoder = GeoCoder.newInstance();
                //设置反地理编码位置坐标
                ReverseGeoCodeOption op = new ReverseGeoCodeOption();
                op.location(new LatLng(AllData.userModel.getLatitude(), AllData.userModel.getLongitude()));
                //发起反地理编码请求(经纬度->地址信息)
                geoCoder.reverseGeoCode(op);
                geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

                    @Override
                    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
                        //获取点击的坐标地址
                        BNRoutePlanNode startPoint = new BNRoutePlanNode(AllData.userModel.getLongitude(), AllData.userModel.getLatitude(), arg0.getAddress(), "起始位置", BNRoutePlanNode.CoordinateType.BD09LL);
                        BNRoutePlanNode endPoint = new BNRoutePlanNode(model.getLongitude(), model.getLatitude(), model.getAddress(), "结束位置", BNRoutePlanNode.CoordinateType.BD09LL);

                        List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
                        list.add(startPoint);
                        list.add(endPoint);
                        if(BaiduNaviManager.isNaviInited())
                            BaiduNaviManager.getInstance().launchNavigator(getActivity(),
                                    list, ROUTE_PLAN_MOD_RECOMMEND, true,
                                    new DemoRoutePlanListener(startPoint));
                    }

                    @Override
                    public void onGetGeoCodeResult(GeoCodeResult arg0) {
                    }
                });
            }
        });

        PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });

        popupWindow.setAnimationStyle(R.style.PopupAnimation);
        popupWindow.showAtLocation(mMapView, Gravity.TOP, 0, 0);
        popupWindow.update();
    }

    private void showOutDetailPopupWindow(final OutPoliceModel data) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(getActivity()).inflate(
                R.layout.popup_out_detail, null);
        // 设置按钮的点击事件

        CircleImageView ivHead = (CircleImageView) contentView.findViewById(R.id.iv_head);
        TextView tvName = (TextView) contentView.findViewById(R.id.tv_name);
        TextView tvHigh = (TextView) contentView.findViewById(R.id.tv_high);
        TextView tvTemp = (TextView) contentView.findViewById(R.id.tv_temp);
        final RelativeLayout layoutRemote = (RelativeLayout) contentView.findViewById(R.id.layout_remote_help);
        final TextView tvRemoteHelp = (TextView) contentView.findViewById(R.id.tv_remote_help);

        if(data.get_id().equals(AllData.outPolice_id)){
            layoutRemote.setVisibility(View.GONE);
        }
        if(remoteHelpModelMap.containsKey(data.get_id())){
            tvRemoteHelp.setText("取消远端报警");
            layoutRemote.setBackground(getActivity().getResources().getDrawable(R.drawable.btn_cancel));
        }
        tvRemoteHelp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!callHelpModelMap.containsKey(data.get_id())) {
                    SendData.data = SendData.sendEnterPoliceData(Integer.parseInt(data.getMid()));
                    SendData.needSend = true;
                    remoteHelpModelMap.put(data.get_id(), data);
                    tvRemoteHelp.setText("取消远端报警");
                    layoutRemote.setBackground(getActivity().getResources().getDrawable(R.drawable.btn_cancel));
                }else {
                    SendData.data = SendData.sendCancelPoliceData(Integer.parseInt(data.getMid()));
                    SendData.needSend = true;
                    remoteHelpModelMap.remove(data.get_id());
                    tvRemoteHelp.setText("激活远端报警");
                    layoutRemote.setBackground(getActivity().getResources().getDrawable(R.drawable.bg_btn_no_tran));
                }
            }
        });
        ivHead.setImageBitmap(usersBitmap.get(data.getUid()));
        tvName.setText("姓名：" + data.getUserName());
        tvHigh.setText("当前高度：" + data.getHigh() + "米");
        tvTemp.setText("当前温度：" + data.getTemp() + "℃");

        PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });

        popupWindow.setAnimationStyle(R.style.PopupAnimation);
        popupWindow.showAtLocation(mMapView, Gravity.TOP, 0, 0);
        popupWindow.update();
    }

    private void showHelpDetailPopupWindow(final CallHelpModel data) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(getActivity()).inflate(
                R.layout.popup_out_detail, null);
        // 设置按钮的点击事件

        CircleImageView ivHead = (CircleImageView) contentView.findViewById(R.id.iv_head);
        TextView tvName = (TextView) contentView.findViewById(R.id.tv_name);
        TextView tvHigh = (TextView) contentView.findViewById(R.id.tv_high);
        TextView tvTemp = (TextView) contentView.findViewById(R.id.tv_temp);
        final RelativeLayout layoutRemote = (RelativeLayout) contentView.findViewById(R.id.layout_remote_help);
        final TextView tvRemoteHelp = (TextView) contentView.findViewById(R.id.tv_remote_help);

        if(data.getOid().equals(AllData.outPolice_id)){
            layoutRemote.setVisibility(View.GONE);
        }
        if(remoteHelpModelMap.containsKey(data.getOid())){
            tvRemoteHelp.setText("取消远端报警");
            layoutRemote.setBackground(getActivity().getResources().getDrawable(R.drawable.btn_cancel));
        }
        tvRemoteHelp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!callHelpModelMap.containsKey(data.getOid())) {
                    SendData.data = SendData.sendEnterPoliceData(Integer.parseInt(data.getMid()));
                    SendData.needSend = true;
                    remoteHelpModelMap.put(data.getOid(), outPoliceModelMap.get(data.get_id()));
                    tvRemoteHelp.setText("取消远端报警");
                    layoutRemote.setBackground(getActivity().getResources().getDrawable(R.drawable.btn_cancel));
                } else {
                    SendData.data = SendData.sendCancelPoliceData(Integer.parseInt(data.getMid()));
                    SendData.needSend = true;
                    remoteHelpModelMap.remove(data.getOid());
                    tvRemoteHelp.setText("激活远端报警");
                    layoutRemote.setBackground(getActivity().getResources().getDrawable(R.drawable.bg_btn_no_tran));
                }
            }
        });
        ivHead.setImageBitmap(usersBitmap.get(data.getUid()));
        tvName.setText("姓名：" + data.getName());
        tvTemp.setText("搜救人：" + data.getHelperName());
        tvHigh.setText("当前高度：" + data.getHigh() + "米");

        PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });

        popupWindow.setAnimationStyle(R.style.PopupAnimation);
        popupWindow.showAtLocation(mMapView, Gravity.TOP, 0, 0);
        popupWindow.update();
    }


    public void getFirePoint(){
        String url =  API.getFirePoints() + "?fid=" + AllData.userModel.getFirecompany_id() + "&state=true";
        JsonObjectRequest ja = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Gson gson = new Gson();
                JSONArray array = null;
                try {
                    array = response.getJSONArray("result");
                    for(int i = 0; i < array.length(); i++){
                        FirePointModel model = new FirePointModel();
                        JSONObject object = array.getJSONObject(i);
                        model = gson.fromJson(String.valueOf(object), FirePointModel.class);
                        AllData.firePointModels.add(model);
                        overLayFirePoint(model);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {}
        });
        RequestQueue queue = UsbApplication.getQueue();
        queue.add(ja);
    }

    private void overLayFirePoint(FirePointModel model) {
        LatLng point = null;
        MarkerOptions option = null;
        point = new LatLng(model.getLatitude(), model.getLongitude());
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.fire_icon);
        Bitmap bitmap1 = LoadImage._8p(bitmap.getBitmap());
        BitmapDescriptor bitmap2 = BitmapDescriptorFactory.fromBitmap(bitmap1);
        option = new MarkerOptions().position(point).icon(bitmap2);
        Marker marker = (Marker) mBaiduMap.addOverlay(option);
        //Bundle用于通信
        Bundle bundle = new Bundle();
        bundle.putSerializable("info", model);
        bundle.putInt("state", 2);
        marker.setExtraInfo(bundle);//将bundle值传入marker中，给baiduMap设置监听时可以得到它
    }

    public class DemoRoutePlanListener implements BaiduNaviManager.RoutePlanListener {

        private BNRoutePlanNode mBNRoutePlanNode = null;

        public DemoRoutePlanListener(BNRoutePlanNode node) {
            mBNRoutePlanNode = node;
        }

        @Override
        public void onJumpToNavigator() {
            Intent intent = new Intent(getActivity(), BNDemoGuideActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("routePlanNode", mBNRoutePlanNode);
            intent.putExtras(bundle);
            startActivity(intent);
        }

        @Override
        public void onRoutePlanFailed() {
            Toast.makeText(getActivity(), "距离过近或过远!", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

}
